package main.java.com.dpbird;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityUtil;
import org.apache.ofbiz.order.order.*;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;
import org.apache.ofbiz.entity.util.EntityQuery;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * openUI的service
 * 
 **/
public class OdataServices {

	/**
	 * 
	 * @param dctx
	 * @param context
	 * @author zhuwenchao
	 * @description 查询订单项的详细统计信息
	 */
	public static Map<String, Object> getOrderItemDetailInfo(DispatchContext dctx, Map<String, ? extends Object> context) {
		Map<String, Object> resultMap = ServiceUtil.returnSuccess();
		LocalDispatcher dispatcher = dctx.getDispatcher();
		Delegator delegator = dctx.getDelegator();
		String orderId = (String) context.get("orderId");
		String orderItemSeqId = (String) context.get("orderItemSeqId");
		try {
			OrderReadHelper orderReadHelper = new OrderReadHelper(delegator, orderId);
			GenericValue orderItem = delegator.findOne("OrderItem", false, UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId));
			BigDecimal quantity = orderItem.getBigDecimal("quantity");
			BigDecimal cancelQuantity = BigDecimal.ZERO;
			if (UtilValidate.isNotEmpty(orderItem.getBigDecimal("cancelQuantity"))) {
				cancelQuantity = orderItem.getBigDecimal("cancelQuantity");
			}
			BigDecimal quantityAccepted = BigDecimal.ZERO;
			BigDecimal quantityRejected = BigDecimal.ZERO;
			BigDecimal unitPrice = BigDecimal.ZERO;

			List<GenericValue> shipmentReceipts = orderItem.getRelated("ShipmentReceipt");
			for (GenericValue shipmentReceipt : shipmentReceipts) {
				quantityAccepted = quantityAccepted.add(shipmentReceipt.getBigDecimal("quantityAccepted"));
				quantityRejected = quantityRejected.add(shipmentReceipt.getBigDecimal("quantityRejected"));
			}

			unitPrice = orderItem.getBigDecimal("unitPrice");
			BigDecimal orderItemTax = orderReadHelper.getOrderItemTax(orderItem);
			BigDecimal orderItemAdjustmentsTotal = orderReadHelper.getOrderItemAdjustmentsTotal(orderItem);
			List<GenericValue> orderItemAdjustmentsTax = orderReadHelper.filterOrderAdjustments(orderReadHelper.getOrderItemAdjustments(orderItem), false, true, false, false, false);
			List<GenericValue> orderItemAdjustments = orderReadHelper.filterOrderAdjustments(orderReadHelper.getOrderItemAdjustments(orderItem), true, false, false, false, false);
			// BigDecimal orderItemQuantity =
			// OrderReadHelper.getOrderItemQuantity(orderItem);
			BigDecimal remainQuantity = quantity.subtract(cancelQuantity).subtract(quantityAccepted).subtract(quantityRejected);
			Map<String, Object> data = new HashMap<>();
			data.put("quantity", quantity);
			data.put("cancelQuantity", cancelQuantity);
			data.put("quantityAccepted", quantityAccepted);
			data.put("quantityRejected", quantityRejected);
			data.put("remainQuantity", remainQuantity);
			data.put("unitPrice", unitPrice);
			data.put("orderItemTax", orderItemTax);
			data.put("orderItemAdjustmentsTotal", orderItemAdjustmentsTotal);
			// 加上税的扣除
			data.put("subtotal", orderReadHelper.getOrderItemSubTotal(orderItem).add(orderItemTax));
			data.put("isModifiedPrice", orderItem.getString("isModifiedPrice"));

			data.put("orderItemAdjustmentsTax", orderItemAdjustmentsTax);
			data.put("orderItemAdjustments", orderItemAdjustments);
			resultMap.put("data", JSONObject.fromObject(data).toString());
		} catch (GenericEntityException e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	public static Map<String, Object> getCategoryTree(DispatchContext dctx, Map<String, ? extends Object> context) {
		Map<String, Object> resultMap = ServiceUtil.returnSuccess();
		LocalDispatcher dispatcher = dctx.getDispatcher();
		Delegator delegator = dctx.getDelegator();
		int limitSize = (Integer) context.get("limitSize");
		String parentCategoryId = (String) context.get("parentCategoryId");

		Map<String,Object> tree = getCategoryTree(delegator,parentCategoryId,limitSize,0);
		JSONObject json = JSONObject.fromObject(tree);
		Debug.log("+++++++++++  " + json.toString());
		resultMap.put("categoryTree", tree);
		return resultMap;
	}
	public static Map<String, Object> getCategoryTreeByCatalogId(DispatchContext dctx, Map<String, ? extends Object> context) {
		Map<String, Object> resultMap = ServiceUtil.returnSuccess();
		LocalDispatcher dispatcher = dctx.getDispatcher();
		Delegator delegator = dctx.getDelegator();
		int limitSize = (Integer) context.get("limitSize");
		String catalogId = (String) context.get("catalogId");
		String prodCatalogCategoryTypeId = (String) context.get("prodCatalogCategoryTypeId");
		
		try {
			List<GenericValue> list =  EntityQuery.use(delegator).from("ProdCatalogCategory").where("prodCatalogId",catalogId,
					"prodCatalogCategoryTypeId",prodCatalogCategoryTypeId).queryList();
			List<Map<String,Object>> pccList = new ArrayList<>();
			for (GenericValue pcc : list) {
				pccList.add(getCategoryTree(delegator,pcc.getString("productCategoryId"),limitSize,0));
			}
			
			JSONArray json = JSONArray.fromObject(pccList);
			Debug.log("+++++++++++  " + json.toString());
			resultMap.put("categoryList", pccList);
		} catch (GenericEntityException e) {
			e.printStackTrace();
		}
		return resultMap;
	}

	public static Map<String, Object> getCategoryTree(Delegator delegator, String parentId, int limitSize, int level) {
		Map<String, Object> categoryMap = new HashMap<>();
		try {
//			List<GenericValue> rollups = delegator.findByAndCache("ProductCategoryRollup", UtilMisc.toMap("parentProductCategoryId", parentId), UtilMisc.toList("sequenceNum"));
			List<GenericValue> rollups = EntityQuery.use(delegator).from("ProductCategoryRollup").where("parentProductCategoryId", parentId).queryList();
			rollups = EntityUtil.filterByDate(rollups);

			categoryMap.put("category", delegator.findOne("ProductCategory", true, UtilMisc.toMap("productCategoryId", parentId)));
			List<Map<String, Object>> children = new ArrayList<>();
			if (level + 1 < limitSize) {
				if (UtilValidate.isNotEmpty(rollups)) {
					for (GenericValue parent : rollups) {

//						GenericValue cv = parent.getRelatedOneCache("CurrentProductCategory");
						// 16 method
						GenericValue cv = parent.getRelatedOne("CurrentProductCategory",true);
						if (UtilValidate.isNotEmpty(cv)) {
							children.add(getCategoryTree(delegator, cv.getString("productCategoryId"), limitSize, level + 1));
						}
					}
					categoryMap.put("children", children);
				}
			}
		} catch (GenericEntityException e) {
			e.printStackTrace();
		}

		return categoryMap;
	}/**
 	 * 
 	 * @param dctx
 	 * @param context
 	 * @author guantianlong
 	 * @description 查询退单的详细统计信息
 	 */
    public static Map<String, Object> getReturnDetailInfo(DispatchContext dctx,Map<String, ? extends Object> context) {
    	Map<String, Object> resultMap = ServiceUtil.returnSuccess();
    	LocalDispatcher dispatcher = dctx.getDispatcher();
    	Delegator delegator = dctx.getDelegator();
    	String returnId=(String) context.get("returnId");
 		try {
// 			List<GenericValue> returnItems = delegator.findByAnd("ReturnItemOpenUiListView", UtilMisc.toMap("returnId", returnId));
 			List<GenericValue> returnItems = EntityQuery.use(delegator).from("ReturnItemOpenUiListView").where("returnId", returnId).queryList();


 			BigDecimal returnQuantitySum = BigDecimal.ZERO;
 			BigDecimal receivedQuantitySum = BigDecimal.ZERO;
 			BigDecimal invoiceAmountSum = BigDecimal.ZERO;
 			
 			for(GenericValue item : returnItems) {
 				BigDecimal returnQuantity = item.getBigDecimal("returnQuantity");
 				BigDecimal receivedQuantity = item.getBigDecimal("receivedQuantity");
 				BigDecimal amountSum = item.getBigDecimal("amountSum");
 				returnQuantitySum = returnQuantitySum.add(UtilValidate.isEmpty(returnQuantity)?BigDecimal.ZERO:returnQuantity);
 				receivedQuantitySum = receivedQuantitySum.add(UtilValidate.isEmpty(receivedQuantity)?BigDecimal.ZERO:receivedQuantity);
 				
 			}
 			
// 			List<GenericValue> returnItemBillings = delegator.findByAnd("ReturnItemBilling", UtilMisc.toMap("returnId", returnId));
 			List<GenericValue> returnItemBillings = EntityQuery.use(delegator).from("ReturnItemBilling").where("returnId", returnId).queryList();
 			for(GenericValue bill : returnItemBillings) {
 				BigDecimal amount = bill.getBigDecimal("amount");
 				BigDecimal quantity = bill.getBigDecimal("quantity");
 				invoiceAmountSum = invoiceAmountSum.add(
 						(UtilValidate.isEmpty(amount)?BigDecimal.ZERO:amount).multiply(UtilValidate.isEmpty(quantity)?BigDecimal.ZERO:quantity)
 								);
 			}
 			
 			Map<String,Object> data = new HashMap<>();
 			data.put("returnQuantitySum", returnQuantitySum);
 			data.put("receivedQuantitySum", receivedQuantitySum);
 			data.put("invoiceAmountSum", invoiceAmountSum);
 			
 			resultMap.put("data", JSONObject.fromObject(data).toString());
 		} catch (GenericEntityException e) {
 			e.printStackTrace();
 		}
    		return resultMap;
    }

}
